/**
 * 账单列表
 */

var billStatuses={"1":" 未结清","2":"已结清","3":"已逾期"};
var pageBean = null;
var dataList = {};
var payableAmount = 0;
var paidAmount = 0;
var noPayment = 0;

$(document).ready(function(e) {	
	initialSpace();

//    $("#searchBeginTime").val(getCurrentMonthFirst().format("yyyy-MM-dd"));
//    $("#searchEndTime").val(getCurrentMonthLast().format("yyyy-MM-dd"));
	
	search(1);
	$("DIV[name='billList']").show();
	$("DIV[name='viewInfo']").hide();	
	$("#btnCloseBillDetail").click(closeBillDetail);
})

/*关闭订单详情页，返回订单列表*/
function closeBillDetail(){
	$("DIV[name='billList']").show();
	$("DIV[name='viewInfo']").hide();	
}

//清空搜索条件
function searchReset(){
	$("#searchBeginTime").val('');
	$("#searchEndTime").val('');
	$("#searchSpace").val('0').trigger("change");
	$("#searchStatus").val('0').trigger("change");
	$("#searchClientName").val('');
}

function getSearchParameter(currentPage){
	try{
		var clientName = $("#searchClientName").val();	
		var dateStart = getCurrentMonthLast().format("yyyy-MM-dd"),//$("#searchBeginTime").val(),
			dateEnd = $("#searchEndTime").val(),
			spaceId = parseInt($("#searchSpace").val()),			
			billStatus	= parseInt($("#searchStatus").val()),
			uname	= $("#searchUserName").val();
			if(spaceId == '0'){
				spaceId = "";
			}
			if(billStatus == '0'){
				billStatus = "";
			}
		var requestJson = {like:{"clientName":clientName},equals:{'dateStart':dateStart,'dateEnd':dateEnd,'spaceId':spaceId,"billStatus":billStatus}}
		return requestJson;
	}catch(e){
		console.log(e.messge);
	}
	return false;
}

function detail(id){
	$("DIV[name='billList']").hide();
	$("DIV[name='viewInfo']").show();	
	var bill = dataList[id];
	if(bill == null){
		return ;
	}
	var billDetailTable = $("#billDetailTable");
	var payableAmount = 0;
	var paidAmount = 0;
	$(billDetailTable).empty();
	$.each(bill.billDetails,function(i,billDetail){
		var html = '<tr>';
		html += '<td>' +  $.trim(billDetail["orderCode"])  + '</td>';
		html += '<td>' + $.trim(billDetail["orderTypeName"]) + '</td>';
		html += '<td>' + $.trim(billDetail["billDescription"]) + '</td>';
		html += '<td>' + $.trim(billDetail["payableAmount"])  + '</td>';
		html += '<td>' + $.trim(billDetail["paidAmount"])  + '</td>';     
		html += '<td>' + $.trim(billDetail["bill_date"])  + '</td>';     
		html += '<td>' + $.trim(billDetail["paymentMode"])  + '</td>';     
		html += '<td>' + $.trim(billDetail["remark"])  + '</td>';     
		html += '</tr>';
		payableAmount = payableAmount + billDetail["payableAmount"];
		paidAmount = paidAmount + billDetail["paidAmount"];
    	$(billDetailTable).append(html);
	});
	$("#infoTitle").html("账单详情-"+bill.clientName);
	$("#ViewInfo1").empty();
	var billStatus = billStatuses[$.trim(bill["billStatus"])];
    if($.trim(bill["billStatus"]) == '3'){
    	billStatus = '<font color="red">'+ billStatus +'</font>'
    }
    
    var date=new Date(bill.billDate);
    var currentMonth=date.getMonth();
    var nextMonth=++currentMonth;
    var nextMonthFirstDay=new Date(date.getFullYear(),nextMonth,1);
    var oneDay=1000*60*60*24;
    var deadline = new Date(nextMonthFirstDay-oneDay).format("yyyy-MM-dd")
    
	var htmlA = '<li><label style="width:150px;">账单状态:</label><label>'+$.trim(billStatus)+'</label></li>';
	htmlA +='<li><label style="width:150px;">账单日：</label><label>'+$.trim(bill.billDate)+'</label></li>';
	htmlA +='<li><label style="width:150px;">最晚回款日：</label><label>'+$.trim(deadline)+'</label></li>';
	htmlA +='<li><label style="width:150px;">应收总额：</label><label>'+$.trim(payableAmount)+'</label></li>';
	htmlA +='<li><label style="width:150px;">回款总额：</label><label>'+$.trim(paidAmount)+'</label></li>';
	$("#ViewInfo1").html(htmlA);
	
	
}
function search(currentPage){

	var requestJson = getSearchParameter(currentPage);
	if(requestJson == false){
		return false;
	}
	requestJson = {currentPage:currentPage,data:requestJson};
	$.ajax({
        url: '/euc/bill/query',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	console.log(JSON.stringify(result));
        	pageBean = result.data;
        	$("#userTable").empty();
        	payableAmount = 0;
        	paidAmount = 0;
        	noPayment = 0;
        	$.each(result.data.list,function(i,data){
        		payableAmount += data["payableAmount"];
        		paidAmount += data["paidAmount"];        		
                var billStatus = billStatuses[$.trim(data["billStatus"])];
                if($.trim(data["billStatus"]) == '3'){
                	billStatus = '<font color="red">'+ billStatus +'</font>'
                }                
        		var bgcolor= localStorage.getItem('trcolor');
        		if(i % 2 == 0){
        			bgcolor = '';
        		}
        		var html = '<tr '+ bgcolor +'>';
        		html += '<td>' +  $.trim(data["billCode"])  + '</td>';
        		html += '<td>' + $.trim(data["spaceName"]) + '</td>';
        		html += '<td>' + $.trim(data["clientName"]) + '</td>';
        		html += '<td>' + $.trim(data["payableAmount"])  + '</td>';
        		html += '<td>' + $.trim(data["paidAmount"])  + '</td>';        		
//        		html += '<td>' + billStatus  + '</td>';
        		html += '<td>未出帐</td>';
        		html += '<td>' + $.trim(data["billDate"])  + '</td>';
              	html += '<td style="width:170px;"><a href="javascript:detail('+data.id+');" class="tablelink">查看</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>';
        		html += '</tr>';
	        	$("#userTable").append(html);
	        	dataList[data.id] = data;
			});
        	noPayment = payableAmount - paidAmount ;
        	$("#total1").html(payableAmount);
        	$("#total1").html(paidAmount);
        	$("#total1").html(noPayment);
        	$("#totalRow").html(pageBean.totalRow+'&nbsp;');
        	$("#currentPage").html(pageBean.currentPage+'&nbsp;');
        	$("#pageSize").html(pageBean.pageSize+'&nbsp;');        	
        	var pageLength = 15;
        	initailPageNumber(pageBean.totalPage,pageBean.currentPage,pageLength);        	
        },
        error: function () {
        	console.log("error");
        }  
    });
}

function initailPageNumber(totalPage,currentPage,pageLength){
	try{
			var midNumber = Math.ceil((pageLength-2)/2);
			var paginList = $(".paginList");
			$(paginList).empty();			
			var prev = '<li class="paginItem"><a href="javascript:;"><span class="pagepre"></span></a></li>';
			var next = '<li class="paginItem"><a href="javascript:;"><span class="pagenxt"></span></a></li>';
			if( totalPage <= pageLength - 2){
				$(prev).appendTo($(".paginList"));
				for(var i = 1; i<totalPage+1; i++){
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
					if(i == currentPage){
						pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
					}			
					$(pagenItem).appendTo($(".paginList"));
				}
				$(next).appendTo($(".paginList"));
			}else{				
				if(currentPage <= midNumber){
					$(prev).appendTo($(".paginList"));
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
						if(i == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
						}			
						$(pagenItem).appendTo($(".paginList"));
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}if(totalPage - currentPage < midNumber){

					var index = totalPage;
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+index+'</a></li>';
						if(index == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+index+'</a></li>';
						}			
						$(pagenItem).prependTo($(".paginList"));
						index--;
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+ 1 +'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					$(next).appendTo($(".paginList"));
				}else if(totalPage - currentPage >= midNumber && currentPage > midNumber){

					pagenItem = '<li class="paginItem current"><a href="javascript:;">'+currentPage+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					var count = midNumber - 3;
					for(var i = 1; i<=count;i++){
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage-i)+'</a></li>';
						$(pagenItem).prependTo($(".paginList"));
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage+i)+'</a></li>';
						$(pagenItem).appendTo($(".paginList"));
					}
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+1	+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}				
			}
			$(".paginItem").click(function(){
				if($(this).hasClass("more")){
					//alert("more");
					return;
				}else if($(this).find(".pagepre").length > 0){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur > 1){
						search(cur - 1);
					}
				}else if($(this).find(".pagenxt").length > 0 ){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur < totalPage){
						search(cur + 1);
					}
				}else{
					var cur = $(this).find("a").html();
					cur = parseInt(cur);
					search(cur);
				}
			});
	}catch(e){
		console.log(e.messge);
	}	
}

/*空间名称*/
function initialSpace(){
	try{
		var spaceString = localStorage.getItem('space');
		spaces = $.parseJSON(spaceString);
	}catch(e){
		console.log(e.messge);
	}
	$.ajax({
        url: '/euc/system/space',
        data:'',
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	try{
	        	$.each(result,function(index,data){	
	        		spaces[data.id] = data;  
	   			});
	        	var spaceJson = JSON.stringify(spaces);
	        	localStorage.setItem('space',spaceJson);
        	}catch(e){
        		console.log(e.message);
        	}
        },
        error: function () {
        	console.log("/euc/system/space error");
        }  
    });
	var spaceSelect = $("#searchSpace");
	$.each(spaces,function(key,space){	
		$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceSelect));
	});
	
}


//获取当前月的第一天
function getCurrentMonthFirst(){
    var date=new Date();
    date.setDate(1);
    return date;
}
//获取当前月的最后一天
function getCurrentMonthLast(){
    var date=new Date();
    var currentMonth=date.getMonth();
    var nextMonth=++currentMonth;
    var nextMonthFirstDay=new Date(date.getFullYear(),nextMonth,1);
    var oneDay=1000*60*60*24;
    return new Date(nextMonthFirstDay-oneDay);
}
Date.prototype.format = function(fmt) {
    var o = {
        "M+" : this.getMonth()+1,                 //月份
        "d+" : this.getDate(),                    //日
        "h+" : this.getHours(),                   //小时
        "m+" : this.getMinutes(),                 //分
        "s+" : this.getSeconds(),                 //秒
        "q+" : Math.floor((this.getMonth()+3)/3), //季度
        "S"  : this.getMilliseconds()             //毫秒
    };
    if(/(y+)/.test(fmt)) {
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    }
    for(var k in o) {
        if(new RegExp("("+ k +")").test(fmt)){
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        }
    }
    return fmt;
}